<template>
  <a-page-header :title="$t('246')">
    <template #extra>
      <a-button type="primary" @click="loadPlan">刷新</a-button>
    </template>
  </a-page-header>
  <a-layout has-sider>
    <a-layout-sider style="background-color: white">
      <a-list item-layout="horizontal" :data-source="lstPlan">
        <template #header>
          <a-button type="link" @click="goNewPlan">新建查询</a-button>
        </template>
        <template #renderItem="{ item }">
          <a-list-item
            class="ListItem"
            :class="{ active: item.selected }"
            @click="selectPlan(item)"
          >
            {{ item.name }}
            <br />
            <a-space-compact block>
              <a-button type="text" @click="goEditPlan(item)"
                ><EditOutlined
              /></a-button>
              <a-button type="text" @click="executePlan(item)"
                ><PlayCircleOutlined
              /></a-button>
              <a-button type="text" danger @click="removePlan(item)"
                ><DeleteOutlined
              /></a-button>
            </a-space-compact>
          </a-list-item>
        </template>
      </a-list>
    </a-layout-sider>
    <a-layout-content>
      <div v-for="(x, idx) in lstQueryResult" :key="idx">
        <a-space
          ><strong>{{ x.title }}</strong
          ><a-button type="link" danger @click="removeQueryResult(idx)"
            ><DeleteOutlined /></a-button
        ></a-space>
        <QueryResultTable :result="x"></QueryResultTable>
      </div>
    </a-layout-content>
  </a-layout>
  <a-drawer
    v-model:open="state.popDetail"
    :bodyStyle="{ padding: '4px' }"
    :headerstyle="{ padding: '4px' }"
    :width="state.popTree ? 800 : 400"
  >
    <a-row :gutter="4">
      <a-col :span="state.treeColSpan" v-show="state.popTree">
        <a-table
          :columns="columns"
          :data-source="treeData"
          size="small"
          :pagination="false"
        />
      </a-col>
      <a-col :span="24 - state.treeColSpan">
        <p>
          结构树&nbsp;&nbsp;
          <a-switch
            v-model:checked="state.popTree"
            @change="state.treeColSpan = state.popTree ? 12 : 0"
          />
        </p>
        <a-divider>名称</a-divider>
        <a-input v-model:value="state.curPlanName"></a-input>
        <a-divider>SQL</a-divider>
        <SqlEditor v-model="state.curPlanSql" :canEdit="true"></SqlEditor>
        <a-space>
          <a-button @click="tryPlan">试运行</a-button>
          <a-button type="primary" @click="savePlan">保存</a-button>
        </a-space>
      </a-col>
    </a-row>
  </a-drawer>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import CommonDefine from "@/component/CommonDefine";
import QueryResultTable from "@/component/query/QueryResultTable.vue";
import { useI18n } from "vue-i18n";
import {
  PlayCircleOutlined,
  DeleteOutlined,
  EditOutlined,
} from "@ant-design/icons-vue";
import SqlEditor from "@/component/field/SqlEditor.vue";

const { t } = useI18n();
const state = reactive({
  sql: "",
  activeKey: "1",
  editMode: 0,
  popDetail: false,
  popTree: false,
  curPlanName: "",
  curPlanId: 0,
  curPlanSql: "",
  treeColSpan: 12,
});
const lstPlan = reactive([]);
const lstQueryResult = ref([]);
const columns = [
  { title: t("129"), dataIndex: "label" },
  { title: t("130"), dataIndex: "code" },
];
const treeData = reactive([]);

const loadModelTree = () => {
  treeData.splice(0, treeData.length);
  CommonDefine.apiGetArm(`/api/v1/model/mine-with-tag`, (d) => {
    d.forEach((item) => {
      treeData.push(item);
    });
  });
};

const loadPlan = () => {
  CommonDefine.clearArray(lstPlan);
  CommonDefine.apiGetArm("/api/v1/query/my-plan", (d) => {
    d.forEach((item) => {
      item.key = item.id;
      item.selected = false;
      lstPlan.push(item);
    });
  });
};

const goNewPlan = () => {
  state.curPlanId = 0;
  state.curPlanName = "";
  state.curPlanSql = "";
  state.popDetail = true;
};

const goEditPlan = (item) => {
  state.curPlanId = item.id;
  state.curPlanName = item.name;
  state.curPlanSql = item.sql;
  state.popDetail = true;
};

const tryPlan = () => {
  if (!CommonDefine.useful(state.curPlanName)) {
    CommonDefine.alert("查询名称不能为空");
    return;
  }
  let pd = {
    name: state.curPlanName,
    sql: state.curPlanSql,
  };
  CommonDefine.apiPostArm("/api/v1/query/try-plan", pd, (d) => {
    lstQueryResult.value.push(d);
  });
};

const removeQueryResult = (idx) => {
  lstQueryResult.value.splice(idx, 1);
};

const executePlan = (item) => {
  state.curPlanId = item.id;
  let pd = {
    id: item.id,
  };
  CommonDefine.apiPostArm("/api/v1/query/exec-plan", pd, (d) => {
    lstQueryResult.value.push(d);
  });
};

const savePlan = () => {
  if (!CommonDefine.useful(state.curPlanName)) {
    CommonDefine.alert("查询名称不能为空");
    return;
  }
  let pd = {
    name: state.curPlanName,
    sql: state.curPlanSql,
  };
  if (state.curPlanId > 0) {
    pd.id = state.curPlanId;
  }
  CommonDefine.apiPostArm("/api/v1/query/save-plan", pd, (d) => {
    CommonDefine.alert("查询保存成功");
    loadPlan();
  });
};

const selectPlan = (item) => {
  lstPlan.forEach((x) => (x.selected = false));
  item.selected = true;
  state.curPlanName = item.name;
  state.curPlanId = item.id;
  state.curPlanSql = item.sql;
};

const removePlan = (item) => {
  let pd = { id: item.id };
  CommonDefine.apiPostArm("/api/v1/query/remove-plan", pd, (d) => {
    CommonDefine.alert("删除成功");
    let idx = lstPlan.findIndex((x) => x.id == item.id);
    lstPlan.splice(idx, 1);
    state.curPlanName = "";
    state.curPlanId = 0;
  });
};

onMounted(() => {
  loadPlan();
  loadModelTree();
});
</script>
